package com.ibm.xml.pre;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Scanner;
import java.util.Timer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Attribute;
import org.dom4j.Branch;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Namespace;

import com.ibm.xml.base.DocumentHandler;
import com.ibm.xml.base.Process;

public class PreProcess extends Process implements PreProcessor {

	@Override
	public void PreProcessDoc(String input, String output) {
		// TODO Auto-generated method stub
		System.out.println("Pre: XML 预处理 开始");
		this.ReadFile(input);

		System.out.println("Pre：删除Head标签");
		deleteHead();

		System.out.println("Pre：删除Body标签");
		deleteBody();

		System.out.println("Pre：选择workflow章节");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		chooseUserItem();

		System.out.println("pre：删除html中无用属性");
		Element root = this.getDoc().getRootElement();
		traversalDeleteAttribute(root);

		System.out.println("Pre：XML 预处理 完成");
		this.WriteFile(output);
	}

	// public void deleteUnusedItem() {
	// Element root = this.getDoc().getRootElement();
	// List elem = root.elements();
	//
	// Iterator iter = elem.iterator();
	// boolean isStartDelete = true;
	// while (iter.hasNext()) {
	// Element h1 = (Element) iter.next();
	// if (h1.getName() == "h1"
	// && h1.getText().equals("Migration: Introduction")) {
	// isStartDelete = false;
	// }
	// if (h1.getName() == "h1"
	// && h1.getText().equals(
	// "Appendix. Accessibility features for CSM")) {
	// isStartDelete = true;
	// }
	// if (isStartDelete) {
	// h1.detach();
	// }
	// }
	// }

	public void deleteUnusedItem(int start, int stop) {
		Element root = this.getDoc().getRootElement();
		List elem = root.elements();

		Iterator iter = elem.iterator();
		int count = 0;
		boolean isStartDelete = true;
		while (iter.hasNext()) {
			Element element = (Element) iter.next();
			if (element.getName() == "h1") {
				count++;
				if (count == start) {
					isStartDelete = false;
				}
				if (count - 1 == stop) {
					isStartDelete = true;
				}
			}
			if (isStartDelete) {
				element.detach();
			}
		}
	}

	public void chooseUserItem() {
		Element root = this.getDoc().getRootElement();
		List elem = root.elements("h1");
		Iterator iter = elem.iterator();
		System.out.println("      章节数:" + elem.size() + "个");
		int count = 0;
		while (iter.hasNext()) {
			count++;
			Element h1 = (Element) iter.next();
			System.out.println("            标题" + count + " ：" + h1.getText());
		}

		int start = 0;
		int stop = 0;
		System.out.print("      请输入开始章节：（输入数字，回车结束）");
		BufferedReader strin = new BufferedReader(new InputStreamReader(
				System.in));
		try {
			start = Integer.parseInt(strin.readLine());
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.print("      请输入结束章节：（输入数字，回车结束）");
		BufferedReader strin1 = new BufferedReader(new InputStreamReader(
				System.in));
		try {
			stop = Integer.parseInt(strin1.readLine());
			// String line = null;
			// while ((line = strin1.readLine()) != null) {
			// stop = Integer.parseInt(line);
			// }
			// Scanner sc = new Scanner(System.in);
			// while (true){
			// stop = sc.nextInt();
			// }

		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		deleteUnusedItem(start, stop);
	}

	public void traversalDeleteAttribute(Element element) {
		List elements = element.elements();
		if (elements.size() == 0) {
			// 没有子元素
		} else {
			// 有子元素
			for (Iterator it = elements.iterator(); it.hasNext();) {
				Element elem = (Element) it.next();
				// 删除属性
				if (elem.getName() == "a") {
					// System.out.println("delete a but href");
					deleteAttr(elem, "href");

				} else
					deleteAttr(elem);
				// 递归遍历
				traversalDeleteAttribute(elem);
			}
		}
	}

	public void deleteAttr(Element element) {
		List<Attribute> list = element.attributes();
		for (int i = 0; i < element.attributes().size(); ++i) {
			Attribute attr = list.get(i);
			attr.detach();
			--i;
		}
	}

	public void deleteAttr(Element element, String href) {// 留下href
		List<Attribute> list = element.attributes();
		Iterator<Attribute> iter = element.attributeIterator();
		// ListIterator<Attribute> iter = list.listIterator();
		// System.out.println("list size:" + list.size());
		List<Attribute> delList = new ArrayList();
		while (iter.hasNext()) {
			Attribute attr = (Attribute) iter.next();
			if (attr.getName() == href && attr.getValue().contains("http://")) {
				// System.out.println(attr.getValue());
			} else {
				delList.add(attr);
			}
		}
		list.removeAll(delList);
		// Attribute hrefAttr = null;
		// for (int i = 0; i < list.size(); i++) {
		// Attribute attr = list.get(0);
		// if (attr.getName() == href && attr.getValue().contains("http://")) {
		// hrefAttr = attr;
		// // 留下所有href为http开头的
		// element.remove(attr);
		// } else {
		// element.remove(attr);
		// }
		// }
		// if (hrefAttr != null)
		// element.addAttribute(hrefAttr.getName(), hrefAttr.getValue());
	}

	public void deleteHead() {
		Element root = this.getDoc().getRootElement();
		Element head = root.element("head");
		root.remove(head);
		root.setName("workflow");
	}

	public void deleteBody() {
		Element root = this.getDoc().getRootElement();
		Element body = root.element("body");
		root.appendContent(body);
		root.remove(body);
	}

	public Boolean match(String str, String regex) {
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(str);
		Boolean b = m.find();
		return b;
	}
}
